import re
import time
import paramiko
import datetime
from global_parameter import sys_log_file_path, get_su_password

"""
            操作系统	    应用系统
区域与账号	oetsky	        oetsky
湖南	    oetsky@28569	oetsky@97258
湖北	    oetsky@21291	oetsky@93625
山东		oetsky@85739	oetsky@67983
山西		oetsky@82936	oetsky@97652
福建		oetsky@75623	oetsky@37268
江苏		oetsky@75638	oetsky@47432
浙江		oetsky@87942	oetsky@45296
广东		oetsky@42583	oetsky@23567
新疆		oetsky@39854	oetsky@57428
安徽		oetsky@57192	oetsky@75614
甘肃		oetsky@27682	oetsky@25263
四川		oetsky@18482	oetsky@97782
"""


def ssh_exe_cmd(ssh, cmd):
    stdin, stdout, stderr = ssh.exec_command(cmd)
    output_str = stdout.read().decode('utf-8')
    return output_str


def channel_exe_cmd(channel, cmd, end_flag="# "):
    channel.send(cmd)
    channel.send("\n")
    buff = ''
    while not buff.endswith(end_flag):
        resp = channel.recv(9999)
        # 出现异常字符时忽略
        buff += resp.decode('utf-8', errors='ignore')
        # print(buff)
    return buff


def wait_time():
    """
    解决零点附近，站端系统更新密码，导致cat命令获取密码为空的问题
    判断逻辑：当前时间小于00:10:00的时候，延时10分钟
    :return:
    """
    now_time = datetime.datetime.now()
    # 将时分秒替换为0，生成00:10:00的时间
    zeroed_datetime = now_time.replace(hour=0, minute=0, second=0) + datetime.timedelta(minutes=10)
    if now_time < zeroed_datetime:
        print(now_time)
        print(zeroed_datetime)
        time.sleep(10 * 60)
        print("当前时间小于00:10:00，已延时十分钟")
        print(datetime.datetime.now())


def get_web_password(ip, port, username, password):
    wait_time()
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    now = datetime.datetime.now()
    str_now = now.strftime("%Y-%m-%d")
    print(str_now)
    ssh.connect(hostname=ip, port=port, username=username, password=password)
    try:
        # output_str = ssh_exe_cmd(ssh, 'sudo /home/oetsky/data/bin/chpwd --debug')
        output_str = ssh_exe_cmd(ssh, get_su_password)
        # print(output_str)
        su_password = output_str[-7:]
        # print(su_password)

        channel = ssh.invoke_shell()
        channel.settimeout(60)  # 这里将超时时间设置为60秒
        time.sleep(0.1)

        channel_exe_cmd(channel, "su", end_flag='密码：')
        channel_exe_cmd(channel, su_password)

        # 执行获取密码命令
        grep_data = channel_exe_cmd(channel,
                                    "cat {}SystemOut.log | grep pwd".format(sys_log_file_path))
        # print(grep_data)
        # match_data = re.findall(r"pwd.+\r", grep_data)
        match_data = re.findall(r"pwd.*?--------------.+\r", grep_data)
        if len(match_data) > 0:
            password_web = match_data[-1][-7:-1]
            return password_web
        else:
            grep_back_data = channel_exe_cmd(channel,
                                             "zcat {}backup/{}/* |grep pwd".format(sys_log_file_path, str_now))
            # print(grep_back_data)
            match_back_data = re.findall(r"pwd.*?--------------.+\r", grep_back_data)
            if len(match_back_data) > 0:
                password_web = match_back_data[0][-7:-1]
                return password_web
            else:
                print("未检测到数据", match_data)
                return None
    except paramiko.ssh_exception.AuthenticationException:
        print('paramiko.ssh_exception.AuthenticationException')
        return None


if __name__ == '__main__':
    password_web = get_web_password("10.16.9.29", port=10088, username="oetsky", password="oetsky@87942")
    print(password_web)
    # wait_time()
